import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import { Menu, Icon, Switch } from 'antd'
import { Link } from 'dva/router'
import menuArray from '../utils/menu'
import pathToRegexp from 'path-to-regexp'
import lodash from 'lodash'

const Menus = ({dispatch, app}) => {

  const { current, openKeys, theme, collapsed } = app;

  const showKeys = openKeys||[];

  const arrayToTree = (array, id = 'id', pid = 'pid', children = 'children') => {
    let data = lodash.cloneDeep(array)
    let result = []
    let hash = {}
    data.forEach((item, index) => {
      hash[data[index][id]] = data[index]
    })

    data.forEach((item) => {
      let hashVP = hash[item[pid]]
      if (hashVP) {
        !hashVP[children] && (hashVP[children] = [])
        hashVP[children].push(item)
      } else {
        result.push(item)
      }
    })
    return result
  }

  /**
   * 数组内查询
   * @param   {array}      array
   * @param   {String}    id
   * @param   {String}    keyAlias
   * @return  {Array}
   */
  const queryArray = (array, key, keyAlias = 'key') => {
    if (!(array instanceof Array)) {
      return null
    }
    const item = array.filter(_ => _[keyAlias] === key)
    if (item.length) {
      return item[0]
    }
    return null
  }

  const menuTree = arrayToTree(menuArray,'id','mpid')

  const levelMap = {}

  //递归生成菜单
  const getMenus = (menuTrees) => {
    return menuTrees.map(item =>{
      if(item.children){
        if(item.mpid){
          levelMap[item.id] = item.mpid
        }
        return (
          <Menu.SubMenu
            key = {item.id}
            title = {
                <span>
                  {item.icon && <Icon type={item.icon} />}
                  <span>{item.name}</span>
                </span>
              }
          >
            {getMenus(item.children)}
          </Menu.SubMenu>
        )
      }
      return (
        <Menu.Item key = {item.id}>
          <Link to = {item.router}>
            {item.icon && <Icon type={item.icon}/>}
            <span>{item.name}</span>
          </Link>
        </Menu.Item>
      )
    })
  }

  const menuItems = getMenus(menuTree);

  //保持选中
  const getAncestorKeys = (key) => {
    let map = {}
    const getParent = (index) => {
      const result = [String(levelMap[index])]
      if (levelMap[result[0]]) {
        result.unshift(getParent(result[0])[0])
      }
      return result
    }
    for (let index in levelMap) {
      if ({}.hasOwnProperty.call(levelMap, index)) {
        map[index] = getParent(index)
      }
    }
    return map[key] || []
  }

  const onOpenChange = (openKeys) => {
    const latestOpenKey = openKeys.find(key => !(showKeys.indexOf(key) > -1))
    const latestCloseKey = showKeys.find(key => !(openKeys.indexOf(key) > -1))
    let nextOpenKeys = []
    if (latestOpenKey) {
      nextOpenKeys = getAncestorKeys(latestOpenKey).concat(latestOpenKey)
    }
    if (latestCloseKey) {
      nextOpenKeys = getAncestorKeys(latestCloseKey)
    }
    dispatch({type:'app/save', payload:{ openKeys: nextOpenKeys }});
  }

  // 寻找选中路由
  let currentMenu
  let defaultSelectedKeys
  for (let item of menuArray) {
    if (item.router && pathToRegexp(item.router).exec(location.pathname)) {
      currentMenu = item
      break
    }
  }
  const getPathArray = (array, current, pid, id) => {
    let result = [String(current[id])]
    const getPath = (item) => {
      if (item && item[pid]) {
        result.unshift(String(item[pid]))
        getPath(queryArray(array, item[pid], id))
      }
    }
    getPath(current)
    return result
  }
  if (currentMenu) {
    defaultSelectedKeys = getPathArray(menuArray, currentMenu, 'mpid', 'id')
  }

  const changeTheme = () => {

      dispatch({type:'app/changeTheme', payload:{ theme: theme }});

  }

  return (
    <div>
      <Menu
        theme={theme}
        mode="inline"
        // openKeys={openKeys}
        // selectedKeys={[current]}
        onOpenChange={onOpenChange}
        // inlineCollapsed={true}
      >
        {menuItems}

        <Menu.SubMenu key="sub3" title={<span><Icon type="setting" /><span>设置</span></span>}>
        <Menu.SubMenu key="sub4" title={<span><Icon type="skin" /><span>皮肤</span></span>}>
          <Menu.Item key="7">Option 9</Menu.Item>
          <Menu.Item key="8">Option 10</Menu.Item>
        </Menu.SubMenu>

          <Menu.Item key="11">Option 11</Menu.Item>
          <Menu.Item key="12">Option 12</Menu.Item>
        </Menu.SubMenu>
        <Menu.SubMenu key="sub5" title={<span><Icon type="team" /><span>主题</span></span>}>
          <Menu.Item key="13">Option 13</Menu.Item>
          <Menu.Item key="14">Option 14</Menu.Item>
          <Menu.Item key="15">Option 15</Menu.Item>
          <Menu.Item key="16">Option 16</Menu.Item>
        </Menu.SubMenu>
        <Menu.SubMenu key="sub6" title={<span><Icon type="phone" /><span>电话</span></span>}>
          <Menu.Item key="17">Option 17</Menu.Item>
          <Menu.Item key="18">Option 18</Menu.Item>
          <Menu.Item key="19">Option 19</Menu.Item>
          <Menu.Item key="20">Option 20</Menu.Item>
        </Menu.SubMenu>
        <Menu.SubMenu key="sub7" title={<span><Icon type="contacts" /><span>通讯录</span></span>}>
          <Menu.Item key="21">Option 21</Menu.Item>
          <Menu.Item key="22">Option 22</Menu.Item>
          <Menu.Item key="23">Option 23</Menu.Item>
          <Menu.Item key="24">Option 24</Menu.Item>
        </Menu.SubMenu>
        <Menu.SubMenu key="sub8" title={<span><Icon type="apple" /><span>苹果</span></span>}>
          <Menu.Item key="25">Option 25</Menu.Item>
          <Menu.Item key="26">Option 26</Menu.Item>
          <Menu.Item key="27">Option 27</Menu.Item>
          <Menu.Item key="28">Option 28</Menu.Item>
        </Menu.SubMenu>
        <Menu.SubMenu key="sub9" title={<span><Icon type="aliwangwang-o" /><span>阿里旺旺</span></span>}>
          <Menu.Item key="29">Option 29</Menu.Item>
          <Menu.Item key="30">Option 30</Menu.Item>
          <Menu.Item key="31">Option 31</Menu.Item>
          <Menu.Item key="32">Option 32</Menu.Item>
        </Menu.SubMenu>
        <Menu.SubMenu key="sub10" title={<span><Icon type="windows" /><span>窗口</span></span>}>
          <Menu.Item key="33">Option 33</Menu.Item>
          <Menu.Item key="34">Option 34</Menu.Item>
          <Menu.Item key="35">Option 35</Menu.Item>
          <Menu.Item key="36">Option 36</Menu.Item>
        </Menu.SubMenu>

      </Menu>
    </div>
  );
};


export default connect(({app})=>({app}))(Menus)
